package db

import (
	"common/logging"

	"gopkg.in/couchbaselabs/gocb.v1"
)

var (
	scene_bucket   *gocb.Bucket
	device_bucket  *gocb.Bucket
	defence_bucket *gocb.Bucket
	domain_bucket  *gocb.Bucket
	log_bucket     *gocb.Bucket
	alarm_bucket   *gocb.Bucket
)

const (
	sceneid_key        = "b2bgateway_sceneid"
	scene_info_prefix  = "sceneid_"
	device_info_prefix = "deviceid_"
	deviceid_key       = "b2bgateway_orderid"
)

const (
	CONF_TYPE_SCENE     = "conf_type_scene"
	CONF_TYPE_SUBDEVICE = "conf_type_subdevice"
)

func InitCouchbase(url string) {
	var err error
	myCluster, _ := gocb.Connect(url)

	scene_bucket, err = myCluster.OpenBucket("b2b_scene", "")
	if err != nil {
		logging.Error("couchbase init scene_bucket fail,url:%s,err:%s", url, err.Error())
		panic("InitCouchbase b2b_scene failed")
	} else {
		logging.Info("InitCouchbase scene_bucket ok,url:%s", url)
	}

	device_bucket, err = myCluster.OpenBucket("b2b_device", "")
	if err != nil {
		logging.Error("couchbase1 init device_bucket fail,url:%s,err:%s", url, err.Error())
		panic("InitCouchbase b2b_device failed")
	} else {
		logging.Info("InitCouchbase device_bucket ok,url:%s", url)
	}

	defence_bucket, err = myCluster.OpenBucket("b2b_defence", "")
	if err != nil {
		logging.Error("couchbase init b2b_defence fail,url:%s,err:%s", url, err.Error())
		panic("InitCouchbase b2b_device failed")
	} else {
		logging.Info("InitCouchbase b2b_defence ok,url:%s", url)
	}

	domain_bucket, err = myCluster.OpenBucket("b2b_domain", "")
	if err != nil {
		logging.Error("couchbase init b2b_domain fail,url:%s,err:%s", url, err.Error())
		panic("InitCouchbase b2b_device failed")
	} else {
		logging.Info("InitCouchbase b2b_domain ok,url:%s", url)
	}

	log_bucket, err = myCluster.OpenBucket("b2b_log", "")
	if err != nil {
		logging.Error("OpenBucket log_bucket fail,url:%s,err:%s", url, err.Error())
		panic("InitCouchbase log_bucket failed")
	} else {
		logging.Info("InitCouchbase log_bucket ok,url:%s", url)
	}

	alarm_bucket, err = myCluster.OpenBucket("b2b_alarm", "")
	if err != nil {
		logging.Error("OpenBucket alarm_bucket fail,url:%s,err:%s", url, err.Error())
		panic("InitCouchbase alarm_bucket failed")
	} else {
		logging.Info("InitCouchbase alarm_bucket ok,url:%s", url)
	}
}
